package com.example.demo01.controller;

import com.example.demo01.entities.Good;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wangxun
 * swagger 地址:
 * http://localhost:8080/swagger-ui/
 */
@RestController
@Api("商品接口集合")
@RequestMapping("/good")
public class GoodSwaggerController {

    private static Map<Integer, Good> goods = new ConcurrentHashMap<>();
    private static Integer initId = 1004;

    static {
        goods.put(1001, new Good(1001, "笔记本", 1000));
        goods.put(1002, new Good(1002, "小米手机", 2000));
        goods.put(1003, new Good(1003, "华为手环", 3000));
    }

    @GetMapping("/getAll")
    @ApiOperation("获取所有商品")
    public Collection<Good> getAll() {
        return goods.values();
    }

    @GetMapping("/getById/{goodId}")
    @ApiOperation("根据商品Id获取商品")
    public Good getById(@PathVariable Integer goodId) {
        return goods.get(goodId);
    }

    @PutMapping("insertGood")
    @ApiOperation("新增商品")
    public String insertGood(@RequestBody Good good) {
        good.setGoodId(initId);
        goods.put(initId, good);
        initId++;
        return "新增成功!";
    }

    @DeleteMapping("/deleteById/{goodId}")
    @ApiOperation("根据商品Id删除商品")
    public String deleteById(@PathVariable Integer goodId) {
        Good good = goods.remove(goodId);
        if (ObjectUtils.isNotEmpty(good)) {
            return "删除商品成功，商品Id: " + goodId;
        }
        return "删除商品失败";
    }

    @PostMapping("/updateById")
    @ApiOperation("更新商品")
    public String updateById(@RequestBody Good good) {
        Good oldGood = goods.get(good.getGoodId());
        if (ObjectUtils.isNotEmpty(oldGood)) {
            goods.put(good.getGoodId(), good);
            return "更新商品成功，商品Id: " + good.getGoodId();
        }
        return "更新商品失败";
    }
}
